<template>
    <view class="details" :style="{paddingTop: paddingHeight + 'px'}">
        <nav-bar title="睡眠"></nav-bar>
        <view class="t-h-container">
            <view class="top_view">
                <view class="date_h">
                    <u-image
                        width="48rpx"
                        height="48rpx"
                        :showMenuByLongpress="false"
                        @click="$u.throttle(dayReduceTap, 1000)"
                        src="http://oss.antaimedical.com/images/static/2024/07/6690f721eb14d0f049f44d4fjy4xzrYAJBuG7f1f413ee9db0c4a498e3ad8017621b0.png"
                        :lazy-load="true"
                    ></u-image>
                    <view class="date_m" @click="showCalendar_ = true">
                        <text>{{ currentSearchTime }}</text>
                        <text class="iconfont icon-ln_sanjiaoxia"></text>
                    </view>
                    <u-image
                        width="48rpx"
                        height="48rpx"
                        :showMenuByLongpress="false"
                        @click="$u.throttle(dayPlusTap, 1000)"
                        src="http://oss.antaimedical.com/images/static/2024/07/6690f735eb14d0f049f44d50JLzReaiikJTQc2681661f1bb789352b3fc054979635a.png"
                        :lazy-load="true"
                    ></u-image>
                </view>
            </view>
            <view class="time-box">
                <view class="wakeDown">
                    <view class="d_t" @click="showWakeDownTime = true">
                        <view class="t-l">
                            <u-image
                                width="72rpx"
                                height="72rpx"
                                :showMenuByLongpress="false"
                                src="http://oss.antaimedical.com/images/pro/2024/10/67122869e4b0d615350f309aaCK0zvXNEjave47ee941397bc7bad5c4ca04ca77215f.png"
                                :lazy-load="true"
                            ></u-image>
                            <text class="text">
                                上床时间
                            </text>
                        </view>
                        <view class="t-r">
                            <view class="time">{{ wakeDownTime }}</view>
                            <view class="b-border"></view>
                        </view>
                    </view>
                </view>
                <view class="wakeUp">
                    <view class="u_t" @click="showWakeUpTime = true">
                        <view class="t-l">
                            <u-image
                                width="72rpx"
                                height="72rpx"
                                :showMenuByLongpress="false"
                                src="http://oss.antaimedical.com/images/pro/2024/10/67122896e4b0d615350f309bSyKdgtnzHs3sd54a1d217696382d0f5b0dd8830c18f4.png"
                                :lazy-load="true"
                            ></u-image>
                            <text class="text">
                                起床时间
                            </text>
                        </view>
                        <view class="t-r">
                            <view class="time">{{ wakeUpTime }}</view>
                            <view class="b-border"></view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="large_button" @click="$u.throttle(add, 1500)" v-if="handleType == 'add'">完成</view>
        <view class="handle_c" v-else>
            <view class="delete_btn" @click="$u.throttle(del, 1500)">删除</view>
            <view class="save_btn" @click="$u.throttle(update, 1500)">保存</view>
        </view>
        <u-datetime-picker
            @confirm="selectWakeUpTime"
            @cancel="showWakeUpTime = false"
            @close="showWakeUpTime = false"
            closeOnClickOverlay
            :show="showWakeUpTime"
            v-model="wakeUpTime"
            mode="time"
        ></u-datetime-picker>
        <u-datetime-picker
            @confirm="selectWakeDownTime"
            @cancel="showWakeDownTime = false"
            @close="showWakeDownTime = false"
            :show="showWakeDownTime"
            v-model="wakeDownTime"
            closeOnClickOverlay
            mode="time"
        ></u-datetime-picker>
        <my-calendar
            :monthNum="36"
            :defaultDate="defaultDate_"
            :maxDate="maxDate"
            @confirm="selectDate_"
            :minDate="minDate"
            :show="showCalendar_"
            color="#545DDE"
            closeOnClickOverlay
            @close="showCalendar_ = false"
        ></my-calendar>
    </view>
</template>

<script>
import {
    addSleepRecord,
    findSleepDayRecord,
    updateSleepRecord,
    findSleepDayRecordByDay,
    delSleepRecord
} from '@/api/index.js'
import myCalendar from '@/components/myCalendar/myCalendar.vue';
import { mapGetters } from 'vuex'
const dayjs = require('@/utils/dayjs.min.js');
export default {
    data () {
        return {
            paddingHeight: uni.getStorageSync('navbarHeight'),
            userId: uni.getStorageSync("userId"),
            defaultDate_: [],
            maxDate: undefined,
            minDate: undefined,
            currentSearchTime: undefined, // 当前查询的时间
            showCalendar_: false, // 日历控件显示
            handleType: 'add',
            recordId: '', // 当前睡眠记录id
            type: 'today',
            today: '', // 当天日期
            showWakeUpTime: false,
            showWakeDownTime: false,
            wakeDownTime: '00:00',
            wakeUpTime: '00:00'
        }
    },
    components: {
        myCalendar,
    },
    computed: {
        ...mapGetters({
            userInfo: 'getUserInfo'
        }),
    },
    onLoad (OPTIONS) {
        this.maxDate = dayjs().format('YYYY-MM-DD');
        this.minDate = dayjs(dayjs(this.maxDate).subtract(2, 'year')).format('YYYY-MM-DD')
        this.currentSearchTime = dayjs().format('YYYY/MM/DD')
        this.defaultDate_[0] = dayjs().format('YYYY-MM-DD');
        this.today = this.defaultDate_[0]
        this.fetchData()
    },
    methods: {
        async fetchData () {
            uni.showLoading({
                title: '加载中...'
            })
            let day = this.currentSearchTime.replaceAll('/', '-')
            let params = {
                userId: this.userId,
                time: day
            }
            try {
                const res = await findSleepDayRecordByDay(params)
                if (res.code == 200) {
                    if (!res.data) { // 无记录为添加
                        this.handleType = 'add'
                        this.wakeDownTime = '00:00'
                        this.wakeUpTime = '00:00'
                    } else { // 有记录修改
                        this.handleType = 'update'
                        this.type = 'today'
                        this.wakeDownTime = res.data.startTime.split(' ')[1].substr(0, 5)
                        this.wakeUpTime = res.data.endTime.split(' ')[1].substr(0, 5)
                        this.recordId = res.data.id
                    }
                }
            } catch (e) {
                //TODO handle the exception
            }
            uni.hideLoading()
        },
        async add () {
            uni.showLoading({
                title: '加载中...'
            })
            let today = this.currentSearchTime.replaceAll('/', '-')
            let params = {
                userId: this.userId,
                bodyId: this.userInfo.id,
                endTime: '',
                startTime: ''
            }
            if (this.wakeDownTime == '00:00' && this.wakeUpTime == '00:00') {
                this.wakeUpTime = '23:59'
            }
            params.endTime = `${today} ${this.wakeUpTime}:00`
            // let yesterday = dayjs(dayjs(today).subtract(1, 'day')).format('YYYY-MM-DD')
            params.startTime = `${today} ${this.wakeDownTime}:00`
            // if (this.type == 'today') {
            // 	params.startTime = `${today} ${this.wakeDownTime}:00`
            // } else {

            // }
            try {
                const res = await addSleepRecord(params)
                uni.hideLoading()
                if (res.code == 200) {
                    uni.showToast({
                        title: '操作成功'
                    })
                    setTimeout(() => {
                        uni.$emit('refreshData')
                        uni.navigateBack()
                    }, 1500)
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            } catch (e) {
                //TODO handle the exception
                uni.hideLoading()
            }
        },
        async update () {
            uni.showLoading({
                title: '加载中...'
            })
            let today = this.currentSearchTime.replaceAll('/', '-')
            let params = {
                userId: this.userId,
                bodyId: this.userInfo.id,
                id: this.recordId,
                endTime: '',
                startTime: ''
            }
            if (this.wakeDownTime == '00:00' && this.wakeUpTime == '00:00') {
                this.wakeUpTime = '23:59'
            }
            params.startTime = `${today} ${this.wakeDownTime}:00`
            params.endTime = `${today} ${this.wakeUpTime}:00`
            // if (this.type == 'today') {
            // } else {
            // 	let yesterday = dayjs(dayjs(today).subtract(1, 'day')).format('YYYY-MM-DD')
            // 	params.startTime = `${yesterday} ${this.wakeDownTime}:00`
            // }
            try {
                const res = await updateSleepRecord(params)
                uni.hideLoading()
                if (res.code == 200) {
                    uni.showToast({
                        title: '修改成功'
                    })
                    uni.$emit('refreshData')
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1500)
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            } catch (e) {
                //TODO handle the exception
                uni.hideLoading()
            }
        },
        async del () {
            uni.showLoading({
                title: '加载中...'
            })
            let params = {
                id: this.recordId
            }
            try {
                const res = await delSleepRecord(params)
                uni.hideLoading()
                if (res.code == 200) {
                    uni.showToast({
                        title: '删除成功'
                    })
                    uni.$emit('refreshData')
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1500)
                }
            } catch (e) {
                //TODO handle the exception
                uni.hideLoading()
            }
        },
        selectWakeUpTime () {
            this.showWakeUpTime = false
        },
        selectWakeDownTime () {
            this.showWakeDownTime = false
        },
        // 上一个选项
        dayReduceTap () {
            let pre = dayjs(dayjs(this.currentSearchTime).subtract(1, 'day')).format('YYYY/MM/DD')
            let min = dayjs(this.minDate).format('YYYY/MM/DD')
            if (!dayjs(pre).isBefore(min)) { // 比对前一天是否是最小天数的前一天
                this.currentSearchTime = pre
                this.fetchData()
            } else {
                uni.showToast({
                    title: '已经是最后一页',
                    icon: 'none'
                })
            }
        },
        // 下一个选项
        dayPlusTap () {
            let next = dayjs(dayjs(this.currentSearchTime).add(1, 'day')).format('YYYY/MM/DD')
            let max = dayjs(this.maxDate).format('YYYY/MM/DD')
            if (!dayjs(next).isAfter(max)) { // 比对后一天是否是最大天数的后一天
                this.currentSearchTime = next
                this.fetchData()
            } else {
                uni.showToast({
                    title: '已经是最后一页',
                    icon: 'none'
                })
            }
        },
        // 最大可选某天控件
        selectDate_ (e) {
            this.currentSearchTime = e[0].replaceAll('-', '/')
            this.defaultDate_[0] = e[0]
            this.fetchData()
            this.showCalendar_ = false
        },
    }
}
</script>


<style lang="scss">
page {
    min-height: 100%;
    background: #f5f6fa;
}
</style>
<style lang="scss" scoped>
.details {
    .top_view {
        margin: 0 48rpx;

        .date_h {
            padding: 48rpx 0 32rpx;

            .date_m {
                background-color: #545dde;
                color: #fff;
                font-size: 24rpx;
            }

            .next_p,
            .pre_p {
                background-color: #545dde;
            }

            .iconfont {
                font-size: 18rpx;
                color: #fff;
            }
        }
    }
    .update_time {
        width: 240rpx;
        height: 48rpx;
        margin: 48rpx auto 0;
        padding: 0 48rpx;
        line-height: 48rpx;
        color: #ffffff;
        font-size: 24rpx;
        background-color: #545dde;
        border-radius: 24rpx;
    }
    .time-box {
        padding: 0 32rpx;
        background: #fff;
        border-radius: 24rpx;
        margin-top: 32rpx;
    }
    .wakeUp,
    .wakeDown {
        width: 100%;
        padding: 32rpx 0;
        .days_tabs {
            display: flex;
            align-items: center;
            height: 80rpx;
            margin-bottom: 32rpx;

            .day {
                width: 100%;
                line-height: 76rpx;
                font-size: 24rpx;
                color: #666d7f;
                border-bottom: 2rpx solid #ffffff;
            }

            .current {
                border-bottom: 4rpx solid #545dde;
            }
        }

        .u_t,
        .d_t {
            height: 118rpx;
            padding: 0 16rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 28rpx;
            color: #666666;
            .t-l {
                display: flex;
                align-items: center;
                justify-content: center;
                .text{
                    margin-left: 24rpx;
                }
            }
            .t-r {
                display: flex;
                flex-direction: column;
                align-items: center;
                color: #333;

                .b-border {
                    width: 98rpx;
                    height: 2rpx;
                    background-color: #545dde;
                    margin-top: 10rpx;
                }

                .time {
                    font-weight: 500;
                    font-size: 32rpx;
                    font-family: PingFangSC-Medium, PingFang SC;
                }
            }
        }
    }

    .wakeUp {
        border-top: 2rpx solid #e6ebf5;
    }

    .large_button {
        position: fixed;
        bottom: 76rpx;
        left: 50%;
        transform: translateX(-50%);
    }
}
</style>